package com.example.text.cyclone



import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.view.View
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import com.example.text.appContext


object WebViewUtils {
    var mUploadMessage: ValueCallback<Uri?>? = null;
    var mUploadCallbackAboveL: ValueCallback<Array<Uri?>?>? = null
    fun initWebViewSettings(webView: WebView, mProgressBar: ProgressBar? = null, onReceiveTitle: ((String?) -> Unit)? = null, openImageChooserActivity: (() -> Unit)? = null) {
        webView.settings.apply {
            cacheMode = WebSettings.LOAD_NO_CACHE
            /* 设置支持Js,必须设置的,不然网页基本上不能看 */
            javaScriptEnabled = true
            /* 设置WebView是否可以由JavaScript自动打开窗口，默认为false，通常与JavaScript的window.open()配合使用。*/
            javaScriptCanOpenWindowsAutomatically = true
            allowUniversalAccessFromFileURLs = true
            allowFileAccess = true
            allowFileAccessFromFileURLs = true
            //setAppCacheEnabled(true)
            /* 设置为true表示支持使用js打开新的窗口 */
            javaScriptCanOpenWindowsAutomatically = true
            /* 大部分网页需要自己保存一些数据,这个时候就的设置下面这个属性 */
            domStorageEnabled = true
            /* 设置为使用webview推荐的窗口 */
            useWideViewPort = true
            /* 设置网页自适应屏幕大小 ---这个属性应该是跟上面一个属性一起用 */
            loadWithOverviewMode = true
            /* HTML5的地理位置服务,设置为true,启用地理定位 */
            setGeolocationEnabled(true)
            /* 设置是否允许webview使用缩放的功能,我这里设为false,不允许 */
            builtInZoomControls = false
            /* 提高网页渲染的优先级 */
            setRenderPriority(WebSettings.RenderPriority.HIGH)
            // 允许http和https混用
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        //设置不让其跳转浏览器
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url?.startsWith("http:") == true || url?.startsWith("https:") == true) {
                    return false
                }
                try {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    appContext.startActivity(intent)
                } catch (e: Exception) {
                }
                return true
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                view ?: return
                view.settings.javaScriptEnabled = true
                super.onPageFinished(view, url)
                addWebViewImageClickListener(view);//待网页加载完全后设置图片点击的监听方法
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                view ?: return
                view.settings.javaScriptEnabled = true
                super.onPageStarted(view, url, favicon)
            }

            private fun addWebViewImageClickListener(webView: WebView) {
                webView.loadUrl(
                    "javascript: (function() {\n" +
                            "\tvar objs = document.getElementsByTagName(\"img\");\n" +
                            "\tvar array = new Array();\n" +
                            "\tfor (var j = 0; j < objs.length; j++) {\n" +
                            "\t\tarray[j] = objs[j].src;\n" +
                            "\t}\n" +
                            "\tfor (var i = 0; i < objs.length; i++) {\n" +
                            "        (function(i){\n" +
                            "            objs[i].onclick = function() {\n" +
                            "\t\t\twindow.AndroidJs.openWebViewImage(i, array);\n" +
                            "\t\t}\n" +
                            "        })(i);\n" +
                            "\t\t\n" +
                            "\t}\n" +
                            "})()"
                )
            }

        }

        // 添加客户端支持
        webView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                onReceiveTitle?.invoke(view?.title)
            }

            // For Android < 3.0
            fun openFileChooser(valueCallback: ValueCallback<Uri?>) {
                mUploadMessage = valueCallback
                openImageChooserActivity?.invoke()
            }

            // For Android  >= 3.0
            fun openFileChooser(valueCallback: ValueCallback<Uri?>, acceptType: String?) {
                mUploadMessage = valueCallback
                openImageChooserActivity?.invoke()
            }

            //For Android  >= 4.1
            fun openFileChooser(valueCallback: ValueCallback<Uri?>, acceptType: String?, capture: String?) {
                mUploadMessage = valueCallback
                openImageChooserActivity?.invoke()
            }

            // For Android >= 5.0
            override fun onShowFileChooser(
                webView: WebView?,
                filePathCallback: ValueCallback<Array<Uri?>?>,
                fileChooserParams: WebChromeClient.FileChooserParams?
            ): Boolean {
                mUploadCallbackAboveL = filePathCallback
                openImageChooserActivity?.invoke()
                return true
            }

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    mProgressBar?.visibility = View.GONE
                } else {
                    if (mProgressBar?.visibility == View.GONE)
                        mProgressBar.visibility = View.VISIBLE
                    mProgressBar?.progress = newProgress
                }
                super.onProgressChanged(view, newProgress)
            }
        }
    }

}